package com.family.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.family.domain.Area;
import com.family.domain.Desk;
import com.family.domain.Evaluate;
import com.family.domain.Food;
import com.family.domain.FoodType;
import com.family.domain.Order;
import com.family.domain.SubFood;
import com.family.inter.IArea;
import com.family.inter.IDesk;
import com.family.inter.IEvaluate;
import com.family.inter.IFood;
import com.family.inter.IFoodtype;
import com.family.inter.IOrder;
import com.family.jsontmp.JsonList;
import com.family.tools.DateFormatUtils;
import com.family.tools.QRUtil;
import com.family.tools.SpringToos;

@Controller
public class Redirect {

    @Resource
    IFoodtype ifoodtype;

    @Resource
    IFood ifood;

    @Resource
    IOrder iorder;

    @Resource
    IDesk idesk;

    @Resource
    IEvaluate ievaluate;

    @Resource
    IArea  iarea;

    /*首页*/
    @RequestMapping("/")
    public String greeting() {
        return "index";
    }

    /*新增用户*/
    @RequestMapping("/show_add_user")
    public String show_add_user(ModelMap model)
    {
        return "adduser";
    }

    /*用户列表*/
    @RequestMapping("/show_userlist")
    public String show_userlist()
    {
        return "show_userlist";
    }



    /*新增角色*/
    @RequestMapping("/show_add_role")
    public String show_add_role()
    {
        return "addRole";
    }

    /*角色列表*/
    @RequestMapping("/show_rolelist")
    public String show_rolelist()
    {
        return "show_rolelist";
    }

    /*区域列表*/
    @RequestMapping("/show_area")
    public String show_area()
    {
        return "show_area";
    }

    /*分区管理*/
    @RequestMapping("/show_deskgroup")
    public String show_deskgroup()
    {
        return "show_deskgroup";
    }




    /*登陆成功*/
    @RequestMapping("/login_success")
    public String login_success(String key,ModelMap model,HttpSession session)
    {
        model.put("key", key);
        return "main";
    }

    /*新增权限*/
    @RequestMapping("/show_add_Authority")
    public String show_add_addAuthority(String id,ModelMap model)
    {
        model.put("id", id);
        return "addAuthority";
    }

    /*新增菜品种类*/
    @RequestMapping("/show_foodgroup")
    public String show_foodgroup()
    {
        return "show_foodgroup";
    }

    /*菜品查询*/
    @RequestMapping("/show_foodtype")
    public String show_foodtype()
    {
        return "show_foodtype";
    }

    /*就餐查询*/
    @RequestMapping("/show_desk")
    public String show_desk()
    {
        return "show_desk";
    }

    /*菜单列表*/
    @RequestMapping("/show_foodlist")
    public String show_foodlist()
    {
        return "show_foodlist";
    }

    /*购物车列表*/
    @RequestMapping("/p_show_carlist")
    public String p_show_carlist(String deskid,ModelMap model)
    {

        Desk tmp = idesk.getDeskById(deskid);
        if(tmp.getOthid()!=null)
        {
            deskid=tmp.getOthid();
        }
        Order order = iorder.getOrderByDeskId(deskid);
        Desk desk = idesk.getDeskById(deskid);
        model.put("desknum", desk.getIdnum());

        model.put("deskid", deskid);
        if(order!=null)
        {
            model.put("orderid", order.getId());
        }

        else
            model.put("orderid", "null");

        return "p_show_carlist";
    }

    /*新增菜单*/
    @RequestMapping("/show_addfood")
    public String show_addfood()
    {
        return "addFood";
    }



    /*手机主页*/
    @RequestMapping("/p_main")
    public String p_main(String deskid,ModelMap model)
    {
        //System.out.println(deskid);
        List<FoodType> ft = ifoodtype.getFoodTypeList();
        Desk desk = idesk.getDeskById(deskid);


        model.put("list", ft);
        model.put("deskid", deskid);
        model.put("desknum", desk.getIdnum());

        return "p_main";
    }

    @RequestMapping("/p_foodListGroup")
    public String p_foodListGroup(String deskid,String id,ModelMap model)
    {
        //System.out.println(id);
        List<Food> arr = new ArrayList<Food>();
        List<Food> list = ifood.getFoodListByType(id);
        for(Food food:list)
        {
            //System.out.println(food.getImage());
            String[] img = food.getImage().split(",");
            food.setImage(img[0]);

            arr.add(food);
        }
        model.put("list", arr);
        model.put("deskid", deskid);
        Order order = iorder.getOrderByDeskId(deskid);
        if(order!=null)
        {
            model.put("flag", order.getFlag());
        }else
        {
            model.put("flag", "0");
        }


        FoodType type = ifoodtype.getFoodTypeById(id);
        model.put("typename", type.getTypename());



        return "p_foodDetail";
    }


    @RequestMapping("/p_showCar")
    public String p_showCar(String deskid,ModelMap model)
    {

        Desk desk = idesk.getDeskById(deskid);
        if(desk!=null)
        {
            if(desk.getOthid()!=null && desk.getOthid().trim().length()>0)
            {
                deskid=desk.getOthid();
            }
        }



        int sum=0;
        List<Food> arr = new ArrayList<Food>();
        Order order = iorder.getOrderByDeskId(deskid);
        if(order==null)
        {
            model.put("amt", "0");
            model.put("count", "0");
            model.put("list", arr);
            return "p_show_Car";
        }

        List<SubFood>  list = ifood.getFoodListByOrderid(order.getId());
        for(SubFood food:list)
        {
            String[] img = food.getImage().split(",");
            food.setImage(img[0]);

            arr.add(food);

            sum+=Integer.parseInt(food.getPrice())*Integer.parseInt(food.getCount());
        }
        model.put("list", arr);
        model.put("orderid", order.getId());
        model.put("deskid", deskid);

        model.put("amt", String.valueOf(sum));

        model.put("flag", order.getFlag());

        model.put("count", list.size());
        return "p_show_Car";
    }


    @RequestMapping("/p_showChat")
    public String p_showChat(String deskid,ModelMap model)
    {


        Desk desk = idesk.getDeskById(deskid);
        model.put("deskid", deskid);
        model.put("desknum", desk.getIdnum());


        return "p_show_Chat";
    }



    @RequestMapping("/showChat")
    public String showChat(String deskid,ModelMap model)
    {


        Desk desk = idesk.getDeskById(deskid);
        model.put("deskid", deskid);
        model.put("desknum", desk.getIdnum());
        model.put("deskname", desk.getDname());

        return "show_Chat";
    }

    @ResponseBody
    @RequestMapping("/p_addMsg")
    public String p_addMsg(String deskid,String msg,String flag,HttpServletRequest request)
    {

        ServletContext application=request.getSession().getServletContext();
        LinkedList<String> arr = (LinkedList<String>)application.getAttribute(deskid);

        HashMap map = (HashMap)application.getAttribute("notify");
        if(map==null)
        {
            HashMap<String, String> msgMap = new HashMap<String, String>();
            application.setAttribute("notify", msgMap);
            map = msgMap;
        }

        if(arr==null)
        {
            LinkedList list = new LinkedList<String>();
            list.addLast(flag+"|"+DateFormatUtils.getJSTime()+"|"+msg);
            application.setAttribute(deskid, list);
            if(flag.equals("0"))
                map.put(deskid, msg);

        }else
        {
            arr.addLast(flag+"|"+DateFormatUtils.getJSTime()+"|"+msg);
            if(flag.equals("0"))
                map.put(deskid, msg);
        }

        return "success";

    }

    @ResponseBody
    @RequestMapping("/p_getMsg")
    public String p_getMsg(String deskid,String index,HttpServletRequest request)
    {
        ServletContext application=request.getSession().getServletContext();
        LinkedList<String> arr = (LinkedList<String>)application.getAttribute(deskid);
        if(arr==null)
        {
            return "null";
        }else
        {
            if(arr.size()==0){
                return "null";
            }
            String msg = arr.get(Integer.parseInt(index));
            if(msg!=null)
                return msg;
            else
                return "null";
        }

    }

    @ResponseBody
    @RequestMapping("/p_getMsgLen")
    public String p_getMsgLen(String deskid,HttpServletRequest request)
    {
        ServletContext application=request.getSession().getServletContext();
        LinkedList<String> arr = (LinkedList<String>)application.getAttribute(deskid);
        if(arr==null)
        {
            return "0";
        }else
        {
            return String.valueOf(arr.size());
        }

    }

    @ResponseBody
    @RequestMapping("/p_getMsgNotify")
    public String p_getMsgNotify(HttpServletRequest request)
    {
        ServletContext application=request.getSession().getServletContext();
        HashMap map = (HashMap)application.getAttribute("notify");
        StringBuffer sb = new StringBuffer();
        if(map==null)
        {
            sb.append("null");
        }else
        {
            Set set = map.keySet();


            Iterator it=  set.iterator();
            while(it.hasNext())
            {

                String did = it.next().toString();
                Desk desk = idesk.getDeskById(did);
                String dmsg = map.get(did).toString();
                sb.append(desk.getIdnum()).append("#");
                sb.append(did).append("#").append(dmsg);
                sb.append("|");
                map.remove(did);
            }
            if(sb.length()>0)
            {
                sb.deleteCharAt(sb.length()-1);
            }else
            {
                sb.append("null");
            }


        }

        sb.append("^");
        List<Area> arrList = iarea.getAreaList();
        for(Area area:arrList)
        {
            sb.append(area.getAreaname()+":");
            sb.append(String.valueOf(idesk.getAreaCount(area.getId())));
            sb.append("    ");
        }

        return sb.toString();

    }

    @ResponseBody
    @RequestMapping("/show_qrImag")
    public String show_qrImag(String id,ModelMap model)
    {

        File dir = new File(UploadAction.prop.getProperty("qrimgpath"));
        if(!dir.exists())
        {
            dir.mkdir();
        }

        Desk desk = idesk.getDeskById(id);
        String path = UploadAction.prop.getProperty("qrimgpath")+desk.getDname()+".gif";
        String url ="http://"+SpringToos.getLocalIp()+":"+UploadAction.prop.getProperty("port")+"/p_main?deskid="+id;
        QRUtil.creatQrImag(url, path);

        System.out.println(path);

        model.put("filename", desk.getDname()+".gif");

        return  desk.getDname()+".gif";
    }

    @RequestMapping("/p_showEvaluate")
    public String p_showEvaluate(String foodid,String orderid,ModelMap model)
    {
        Food food = ifood.findById(foodid);
        String[] img = food.getImage().split(",");
        food.setImage(img[0]);

        model.put("food", food);
        model.put("foodid", foodid);
        model.put("orderid", orderid);

        return "p_showEvaluate";
    }

    @ResponseBody
    @RequestMapping("/addEvaluate")
    public String addEvaluate(String foodid,String orderid,String remark,String score)
    {
        char[] t1 = null;
        t1 = remark.toCharArray();
        StringBuffer sb = new StringBuffer();

        int t0 = t1.length;
        int count = 0;
        for (int i = 0; i < t0; i++) {
//        	 if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
//        		 count ++;
//
//        	 }
            if(count<30)
            {
                count++;
                sb.append(Character.toString(t1[i]));
            }else
            {
                sb.append("...");
                break;
            }
        }


        ievaluate.delEvluateByorgId(orderid);

        Evaluate ev = new Evaluate();

        UUID uuid = UUID.randomUUID();
        ev.setId(uuid.toString());

        ev.setFoodid(foodid);
        ev.setOrgid(orderid);
        ev.setRemark(sb.toString());
        ev.setScore(score);
        ev.setEvdate(DateFormatUtils.getCurDate());
        ev.setEvtime(DateFormatUtils.getCurTime());

        ievaluate.addEvluate(ev);

        Map map = new HashMap<String, String>();
        map.put("orgid", orderid);
        map.put("evid", uuid.toString());
        iorder.upEvIdById(map);

        return "success";
    }


    @ResponseBody
    @RequestMapping("/changeDesk")
    public String changeDesk(String srcDeskid,String destNum)
    {
        Desk dest = idesk.getDeskByNum(destNum);
        if(dest==null)
        {
            return "0";
        }
        if(dest.getFlag().equals("2"))
        {
            return "2";
        }
        if(dest.getFlag().equals("0"))
        {
            Map map = new HashMap<String, String>();
            map.put("srcid", srcDeskid);
            map.put("destid", dest.getId());

            /*t_order表 将订单表中deskid改成要换得deskid*/
            iorder.upDeskId(map);

            Map destmap = new HashMap<String, String>();
            Desk src = idesk.getDeskById(srcDeskid);

            destmap.put("flag", src.getFlag());
            destmap.put("time", src.getBegintime());
            destmap.put("id", dest.getId());

            /*t_desk表将原台信息记录到新台上*/
            idesk.upDeskInfo(destmap);

            Map srcmap = new HashMap<String, String>();
            srcmap.put("flag", "0");
            srcmap.put("time", "");
            srcmap.put("id", srcDeskid);

            /*t_desk 清空原台信息*/
            idesk.upDeskInfo(srcmap);
        }else if(dest.getFlag().equals("1"))
        {
            Order destOrder = iorder.getOrderByDeskId(dest.getId());

            Order srcOrder = iorder.getOrderByDeskId(srcDeskid);

            Map map = new HashMap<String, String>();
            map.put("sorderid", srcOrder.getId());
            map.put("dorderid", destOrder.getId());

            /*t_order_food表 将原台订单信息修改程目标台订单中*/
            iorder.upSwitchOrgId(map);

            /*t_order 删除原台订单信息*/
            iorder.delOrderById(srcOrder.getId());

            Desk tmp = idesk.getDeskById(srcDeskid);
            tmp.setFlag("2");
            tmp.setBegintime("");
            tmp.setOthid(dest.getId());

            /*t_desk 将原台信息改为合并*/
            idesk.upDeskColInfo(tmp);

        }


        return "success";
    }

    @ResponseBody
    @RequestMapping("/joinDesk")
    public String joinDesk(String srcDeskid,String destNum)
    {
        Desk dest = idesk.getDeskByNum(destNum);
        if(dest==null)
            return "0";

        Desk src = idesk.getDeskById(srcDeskid);
        src.setFlag("2");
        src.setBegintime("");

        if(dest.getFlag().equals("2"))
        {
            src.setOthid(dest.getOthid());
        }else
        {
            src.setOthid(dest.getId());
        }

        idesk.upDeskColInfo(src);

        List<Desk> list = idesk.getDeskByOthId(src.getId());
        for(Desk desk:list)
        {
            if(desk!=null)
            {
                desk.setFlag("2");
                if(dest.getFlag().equals("2"))
                {
                    desk.setOthid(dest.getOthid());
                }else
                {
                    desk.setOthid(dest.getId());
                }
                desk.setBegintime("");
                idesk.upDeskColInfo(desk);
            }
        }

        return "success";
    }

    @ResponseBody
    @RequestMapping("/cancelDesk")
    public String cancelDesk(String deskid)
    {


        Desk src = idesk.getDeskById(deskid);
        src.setFlag("0");
        src.setOthid("");
        src.setBegintime("");

        idesk.upDeskColInfo(src);

        return "success";
    }

    @RequestMapping("/show_orderlist")
    public String show_orderlist()
    {
        return "show_orderlist";
    }

    @RequestMapping("/show_OrderCount")
    public String show_OrderCount()
    {
        return "show_OrderCount";
    }

    @RequestMapping("/show_footevsort")
    public String show_footevsort()
    {
        return "show_foodEvSort";
    }

    @RequestMapping("/show_foodCount")
    public String show_foodCount()
    {
        return "show_foodCount";
    }


    /*手机端快速查询*/
    @RequestMapping("/p_search")
    public String p_search(String deskid,ModelMap model)
    {
        model.put("deskid", deskid);
        return "p_search";
    }


    @ResponseBody
    @RequestMapping("/delOrder")
    public String delOrder(String orderid)
    {

        Order order = iorder.getOrderById(orderid);
        iorder.delOrderById(orderid);
        iorder.delOrdFoodByOrgId(orderid);

        Desk src = idesk.getDeskById(order.getDeskid());
        src.setFlag("0");
        src.setOthid("");
        src.setBegintime("");

        idesk.upDeskColInfo(src);

        return "success";
    }

}
